/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution3 {
    /**
     * 删除所有值为val的元素
     *
     * @param head
     * @param val
     * @return
     */
    public static ListNode removeElements(ListNode head, int val) {
        if (head == null) return head;
        //得到更小规模问题的解
        ListNode res = removeElements(head.next, val);
        //如果head这个节点满足删除条件
        if (head.val == val) {
            return res;
        } else {
            head.next = res;
            return head;
        }
    }

    /**
     * 简化写法1
     *
     * @param head
     * @param val
     * @return
     */
    public static ListNode removeElements2(ListNode head, int val) {
        if (head == null) return head;
        //得到更小规模问题的解
        head.next = removeElements(head.next, val);
        //如果head这个节点满足删除条件
        if (head.val == val) {
            return head.next;
        } else {
            return head;
        }
    }

    /**
     * 简化写法三
     *
     * @param head
     * @param val
     * @return
     */
    public static ListNode removeElements3(ListNode head, int val) {
        if (head == null) return head;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 6, 3, 4, 5, 6};
        ListNode listNode = new ListNode(nums);
        System.out.println("listNode = " + listNode);
        Solution3.removeElements(listNode, 6);
        System.out.println("listNode = " + listNode);
    }
}